package com.hfzy.ihk.web.ivr.support.callin.handler;

import com.hfzy.ihk.common.eventSocket.constant.EventSubClassName;
import com.hfzy.ihk.common.eventSocket.enums.EventName;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.facade.ivr.vo.FreeswitchCallState;
import com.hfzy.ihk.web.ivr.biz.FreeswitchAsrCallSpeakStateBiz;
import com.hfzy.ihk.web.ivr.biz.FreeswitchAsrCallStateBiz;
import com.hfzy.ihk.web.ivr.constant.RedisKey;
import com.hfzy.ihk.web.ivr.context.EventSocketInitBean;
import com.hfzy.ihk.web.ivr.support.callin.event.FreeswitchCallStateEvent;
import com.hfzy.ihk.web.ivr.support.disruptor.base.DisruptorHandlerAdapter;
import org.freeswitch.esl.client.transport.event.EslEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Created by Administrator on 2019/6/17.
 */
@Component
@Scope("prototype")
public class FreeswitchAsrCallSpeakStateHandler implements DisruptorHandlerAdapter<FreeswitchCallStateEvent> {

    Logger logger = LoggerFactory.getLogger(FreeswitchAsrCallSpeakStateHandler.class);

    @Autowired
    FreeswitchAsrCallSpeakStateBiz freeswitchAsrCallSpeakStateBiz;

    @Autowired
    FreeswitchAsrCallStateBiz freeswitchAsrCallStateBiz;

    @Override
    public void onEvent(FreeswitchCallStateEvent event, long sequence, boolean endOfBatch) throws Exception {
        try {
            Long old = System.currentTimeMillis();

            // procces(event.getData());

            old = System.currentTimeMillis()-old;
            logger.debug("ivr FreeswitchAsrCallSpeakStateHandler handle use time:{}",old);
        } catch (Exception e) {
            logger.error("ivr FreeswitchAsrCallSpeakStateHandler exception",e);
        }
    }

    @Override
    public void onEvent(FreeswitchCallStateEvent event) throws Exception {
        try {
            Long old = System.currentTimeMillis();

            procces(event.getData());

            old = System.currentTimeMillis()-old;
            logger.debug("ivr FreeswitchAsrCallSpeakStateHandler handle use time:{}",old);
        } catch (Exception e) {
            logger.error("ivr FreeswitchAsrCallSpeakStateHandler exception",e);
        }
    }

    /**
     * 流程方法
     * @param state
     */
    protected void procces(FreeswitchCallState state){
        EslEvent event = state.getEvent();
        String eventName = event.getEventName();
        Map<String, String> eventHeaders = event.getEventHeaders();
        String sessionId = eventHeaders.get("Channel-Call-UUID");
        /**自定义的消息中sessionId的值就是sessionId字段，而没有Channel-Call-UUID*/
        if(StringTools.isEmpty(sessionId)){
            sessionId = eventHeaders.get("sessionId");
        }
        //阿里云返回的
        if(StringTools.isEmpty(sessionId)){
            sessionId = eventHeaders.get("session_id");
        }
        String customerSpeakKey = sessionId+ RedisKey.CUSTOMER_SPEAK_STATE;//客户说话状态key
        String robotSpeakKey = sessionId+RedisKey.ROBOT_SPEAK_STATE;//机器人播放录音状态key
        String customerSpeakState = EventSocketInitBean.getCustomerConnection().get(customerSpeakKey);
        String robotSpeakState = EventSocketInitBean.getCustomerConnection().get(robotSpeakKey);
        switch (EventName.fromName(eventName)){
            case CUSTOM :
                String subclass = eventHeaders.get("Event-Subclass");
                switch (subclass){
                    //case EventSubClassName.VAD_START:
                    case EventSubClassName.ALIBABA_ASR_ON_SENTENCE_BEGIN:
                        logger.info("客户开始说话，sessionId：{}",sessionId);
                        if(StringTools.isNotempty(robotSpeakState)&&StringTools.isNotempty(customerSpeakState)&&"true".equals(robotSpeakState)){//第一段录音不打断
                            //打断机器人播放录音
                            freeswitchAsrCallSpeakStateBiz.sendAsyncApiCommand("uuid_playback_stop",sessionId);
                        }
                        EventSocketInitBean.getCustomerConnection().put(customerSpeakKey,"true");//客户说话状态标识为true
                        break;
                    //case EventSubClassName.VAD_STOP:
                    case EventSubClassName.ALIBABA_ASR_ON_SENTENCE_END:
                        logger.info("客户结束说话，sessionId：{}",sessionId);
                        EventSocketInitBean.getCustomerConnection().put(customerSpeakKey,"false");//客户一句话结束标识
                        freeswitchAsrCallStateBiz.handleAlibabaAsr(event);
                        break;
                    default:break;
                }
                break;
            case PLAYBACK_START:
                logger.info("开始播放录音，sessionId：{},客户是否在说话：{}，机器人是否在播放录音：{}",sessionId,customerSpeakState,robotSpeakState);
                if(StringTools.isNotempty(robotSpeakState)&&StringTools.isNotempty(customerSpeakState)&&"true".equals(customerSpeakState)){//第一段录音不打断
                    //打断机器人播放录音
                    freeswitchAsrCallSpeakStateBiz.sendAsyncApiCommand("uuid_playback_stop",sessionId);
                }else{
                    EventSocketInitBean.getRobotConnection().put(robotSpeakKey,"true");
                }
                break;
            case PLAYBACK_STOP:
                logger.info("结束播放录音，sessionId：{}",sessionId);
                EventSocketInitBean.getRobotConnection().put(robotSpeakKey,"false");
                break;
            default:break;
        }
    }

}
